//日期时间 
$(function() {
	$('.date-picker').datepicker();
})

$(".deparment").click(function() {
	$("#deparment").show();
	$.ajax({
		url : ctx + '/cms/index',
		type : 'POST',
		data : {
			enable: 1
		},
		dataType : 'text',
		success : function(data) {
			var _data = eval("(" + data + ")");
			_data.forEach(function(x,y){
				x['pId'] = x['preId'];
				x['open'] = false;
				x['t'] = '';
				delete x['preId'];
				delete x['isComments'];
				delete x['createTime'];
				delete x['enable'];
				delete x['isAudit'];
				delete x['icon'];
				delete x['url'];
				delete x['description'];
				delete x['model'];
				delete x['keyword'];
				delete x['target'];
				delete x['preName'];
			});
			$.fn.zTree.init($("#tree2"), setting, _data);
		},
		error : function(msg) {
			toastr.error('树加载异常!');
		}
	});
});

$(".close,._close").click(function() {
	$("#deparment").hide();
});
$("#tab-add").click(function(){
	$("#columnId").val("");
	$("#colId").val("");
});

$(".insert").click(function(){
	if(!$("#columnId").val()){
		toastr.error('请选择栏目!');
		return false;
	}
	if(!$("#title").val()){
		toastr.error('请输入标题!');
		return false;
	}
	$("#content").val($("#editor").html());
	$.ajax({
		url : ctx + '/cms/saveContent',
		type : 'POST',
		data : $("#insertContent").serialize(),
		dataType : 'text',
		success : function(data) {
			if(data > 0){
				toastr.success('添加成功!');
				window.location.href=ctx+"/cms/content"; 
			}else{
				toastr.error('添加失败!');
			}
		},
		error : function(msg) {
			toastr.error('系统错误!');
		}
	});
});

function editClass(id){
	$.ajax({
		url : ctx + '/cms/findContentById',
		type : 'POST',
		data : {id:id},
		dataType : 'json',
		success : function(data) {
			$("#id2").val(data["id"]);
			$("#title2").val(data["title"]);
			$("#colId2").val(data["columnName"]);
			$("#columnId2").val(data["columnId"]);
			$("#keyword2").val(data["keyword"]);
			$("#weightNum2").val(data["weightNum"]);
			$("#overdueDate2").val(data["overdueDate"]);
			$("#description2").val(data["description"]);
			$("#icon2").val(data["icon"]);
			$("#menu-icon2").attr("class","fa "+data["icon"]).text(data["icon"]);
			$("#editor2").html(data["content"]);
			$("#content2").val(data["content"]);
			$("#fromName2").val(data["fromName"]);
			$("#editUser").find("input[type=radio][name='isComments'][value='"+data["isComments"]+"']").attr("checked",'checked');
			$("#releaseDate2").val(data["releaseDate"]);
			$("#editUser").find("input[type=radio][name='releaseState'][value='"+data["releaseState"]+"']").attr("checked",'checked');
			
			$('#tab-edit').show();
			$('#tab-edit').click();
		},
		error : function(msg) {
			toastr.error('系统错误!');
		}
	});
}

$(".btn-bottm").click(function(){
	$("#tab-list").parent().attr("class","active");
	$("#tab-add").parent().removeClass("active");
	$("#tab-edit").parent().removeClass("active");
	$("#tab-edit").css("display","none");
	$("#home").addClass("active");
	$("#profile").removeClass("active");
	$("#editUser").removeClass("active");
});

$(".edit").click(function(){
	$("#content2").val($("#editor2").html());
	$.ajax({
		url : ctx + '/cms/editContent',
		type : 'POST',
		data : $("#edit").serialize(),
		dataType : 'text',
		success : function(data) {
			if(data > 0){
				toastr.success('修改成功!');
				window.location.href=ctx+"/cms/content"; 
			}else{
				toastr.error('修改失败!');
			}
		},
		error : function(msg) {
			toastr.error('系统错误!');
		}
	});
});

function delClass(id){
	$.ajax({
		url : ctx + '/cms/delContent',
		type : 'POST',
		data : {id:id},
		dataType : 'json',
		success : function(data) {
			if(data > 0){
				toastr.success('删除成功!');
				window.location.href=ctx+"/cms/content"; 
			}else{
				toastr.error('删除失败!');
			}
		},
		error : function(msg) {
			toastr.error('系统错误!');
		}
	});
}
// Ztree和tab的距离
var x = $(".page-body").width();
$(".tabbable").css({
	width : x - 200
});
$(window).resize(function() {
	var x = $(".page-body").width();
	$(".tabbable").css({
		width : x - 200
	});
})

// ZTree中内容
var setting = {
	view : {
		selectedMulti : false
	},
	data : {
		key : {
			title : "t"
		},
		simpleData : {
			enable : true
		}
	},
	callback : {
//		beforeClick : beforeClick,
//		beforeCollapse : beforeCollapse,
//		beforeExpand : beforeExpand,
//		onCollapse : onCollapse,
//		onExpand : onExpand,
		onClick : onClick
	}
};

var setting2 = {
		view : {
			selectedMulti : false
		},
		data : {
			key : {
				title : "t"
			},
			simpleData : {
				enable : true
			}
		},
		callback : {
//			beforeClick : beforeClick,
//			beforeCollapse : beforeCollapse,
//			beforeExpand : beforeExpand,
//			onCollapse : onCollapse,
//			onExpand : onExpand,
			onClick : onClick2
		}
	};

var log, className = "dark";
function onClick(event, treeId, treeNode, clickFlag) {
	$("#colId").val(treeNode.name);
	$("#columnId").val(treeNode.id);
	$("#colId2").val(treeNode.name);
	$("#columnId2").val(treeNode.id);
	$("#deparment").hide();
}

function onClick2(event, treeId, treeNode, clickFlag) {
	$("#_columnId").val(treeNode.id);
	$("#_title").val("");
	$("#_releaseState").val("");
	$("#hiddens").submit();
}

//function beforeClick(treeId, treeNode) {
//	if (treeNode.isParent) {
//		return true;
//	} else {
//		// alert("这个 Demo 是用来测试 展开 / 折叠 的...\n\n去点击父节点吧... ");
//		return false;
//	}
//}
//function beforeCollapse(treeId, treeNode) {
//	className = (className === "dark" ? "" : "dark");
//	showLog("[ " + getTime() + " beforeCollapse ]&nbsp;&nbsp;&nbsp;&nbsp;"
//			+ treeNode.name);
//	return (treeNode.collapse !== false);
//}
//function onCollapse(event, treeId, treeNode) {
//	showLog("[ " + getTime() + " onCollapse ]&nbsp;&nbsp;&nbsp;&nbsp;"
//			+ treeNode.name);
//}
//function beforeExpand(treeId, treeNode) {
//	className = (className === "dark" ? "" : "dark");
//	showLog("[ " + getTime() + " beforeExpand ]&nbsp;&nbsp;&nbsp;&nbsp;"
//			+ treeNode.name);
//	return (treeNode.expand !== false);
//}
//function onExpand(event, treeId, treeNode) {
//	showLog("[ " + getTime() + " onExpand ]&nbsp;&nbsp;&nbsp;&nbsp;"
//			+ treeNode.name);
//}
function showLog(str) {
	if (!log)
		log = $("#log");
	log.append("<li class='" + className + "'>" + str + "</li>");
	if (log.children("li").length > 8) {
		log.get(0).removeChild(log.children("li")[0]);
	}
}
function getTime() {
	var now = new Date(), h = now.getHours(), m = now.getMinutes(), s = now
			.getSeconds(), ms = now.getMilliseconds();
	return (h + ":" + m + ":" + s + " " + ms);
}

function expandNode(e) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), type = e.data.type, nodes = zTree
			.getSelectedNodes();
	if (type.indexOf("All") < 0 && nodes.length == 0) {
		alert("请先选择一个父节点");
	}

	if (type == "expandAll") {
		zTree.expandAll(true);
	} else if (type == "collapseAll") {
		zTree.expandAll(false);
	} else {
		var callbackFlag = $("#callbackTrigger").attr("checked");
		for (var i = 0, l = nodes.length; i < l; i++) {
			zTree.setting.view.fontCss = {};
			if (type == "expand") {
				zTree.expandNode(nodes[i], true, null, null, callbackFlag);
			} else if (type == "collapse") {
				zTree.expandNode(nodes[i], false, null, null, callbackFlag);
			} else if (type == "toggle") {
				zTree.expandNode(nodes[i], null, null, null, callbackFlag);
			} else if (type == "expandSon") {
				zTree.expandNode(nodes[i], true, true, null, callbackFlag);
			} else if (type == "collapseSon") {
				zTree.expandNode(nodes[i], false, true, null, callbackFlag);
			}
		}
	}
}
$(document).ready(function() {
	
	$.ajax({
		url : ctx + '/cms/index',
		type : 'POST',
		data : {
			enable: 1
		},
		dataType : 'text',
		success : function(data) {
			var _data = eval("(" + data + ")");
			_data.forEach(function(x,y){
				x['pId'] = x['preId'];
				x['open'] = false;
				x['t'] = '';
				delete x['preId'];
				delete x['isComments'];
				delete x['createTime'];
				delete x['enable'];
				delete x['isAudit'];
				delete x['icon'];
				delete x['url'];
				delete x['description'];
				delete x['model'];
				delete x['keyword'];
				delete x['target'];
				delete x['preName'];
			});
			$.fn.zTree.init($("#treeDemo"), setting2, _data);
		},
		error : function(msg) {
			toastr.error('树加载异常!');
		}
	});
	
	
	/*$("#expandBtn").bind("click", {
		type : "expand"
	}, expandNode);
	$("#collapseBtn").bind("click", {
		type : "collapse"
	}, expandNode);
	$("#toggleBtn").bind("click", {
		type : "toggle"
	}, expandNode);
	$("#expandSonBtn").bind("click", {
		type : "expandSon"
	}, expandNode);
	$("#collapseSonBtn").bind("click", {
		type : "collapseSon"
	}, expandNode);
	$("#expandAllBtn").bind("click", {
		type : "expandAll"
	}, expandNode);
	$("#collapseAllBtn").bind("click", {
		type : "collapseAll"
	}, expandNode);*/
});

// table 的编辑与删除
$(".editClass_1").on('click', function() {
	editClass_1(this)
});
// 编辑
function editClass_1(_this) {
	$('#tab-edit').show();
	$('#tab-edit').click();
}
$(".removeClass").on('click', function() {
	removeClass(this)
});
// 删除
function removeClass(_this) {
	$(_this).parent().parent().remove();
}
$('#tab-add,#tab-list').click(function() {
	$('#tab-edit,#tab-allocate').hide();
})

// 权重
$(".top input").click(function() {
	if (this.checked) {
		$(this).parents().find("#weight").val(999);
	} else {
		$(this).parents().find("#weight").val("");
	}

});

//选择图标
$(".fa-hover").click(function() {
	var icon = $(this).find("i").attr("class");
	$('i#menu-icon').removeClass().addClass(icon).text(icon.substr(2));
	$("#icon").val(icon.substr(2));
	$("#selectIcon").modal('hide');
})

// edit
$(function() {
	function initToolbarBootstrapBindings() {
		var fonts = [ 'Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
				'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact',
				'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
				'Times New Roman', 'Verdana' ], fontTarget = $('[title=Font]')
				.siblings('.dropdown-menu');
		$.each(fonts, function(idx, fontName) {
			fontTarget.append($('<li><a data-edit="fontName ' + fontName
					+ '" style="font-family:\'' + fontName + '\'">' + fontName
					+ '</a></li>'));
		});
		$('a[title]').tooltip({
			container : 'body'
		});
		$('.dropdown-menu input').click(function() {
			return false;
		}).change(
				function() {
					$(this).parent('.dropdown-menu').siblings(
							'.dropdown-toggle').dropdown('toggle');
				}).keydown('esc', function() {
			this.value = '';
			$(this).change();
		});

		$('[data-role=magic-overlay]').each(
				function() {
					var overlay = $(this), target = $(overlay.data('target'));
					overlay.css('opacity', 0).css('position', 'absolute')
							.offset(target.offset()).width(target.outerWidth())
							.height(target.outerHeight());
				});
		if ("onwebkitspeechchange" in document.createElement("input")) {
			var editorOffset = $('#editor').offset();
			$('#voiceBtn').css('position', 'absolute').offset({
				top : editorOffset.top,
				left : editorOffset.left + $('#editor').innerWidth() - 35
			});
		} else {
			$('#voiceBtn').hide();
		}
	}
	;

	function showErrorAlert(reason, detail) {
		var msg = '';
		if (reason === 'unsupported-file-type') {
			msg = "Unsupported format " + detail;
		} else {
			console.log("error uploading file", reason, detail);
		}
		$(
				'<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>'
						+ '<strong>File upload error</strong> '
						+ msg
						+ ' </div>').prependTo('#alerts');
	}
	;
	initToolbarBootstrapBindings();
	$('.wysiwyg-editor').wysiwyg({
		fileUploadError : showErrorAlert
	});
	window.prettyPrint && prettyPrint();
});
